package com.lkm.app_ui.m.Imple.app_info;

import com.google.gson.JsonObject;
import com.lkm.app_ui.AppConfig;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.AppHelp;
import com.lkm.app_ui.help.GsonHelp;
import com.lkm.app_ui.m.app_info.AppInfoScModule;
import com.lkm.app_ui.m.app_info.AppInfoWrapTo;
import com.lkm.comlib.task2.DefaultTaskExecutor;
import com.lkm.frame.file.FileHelper;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.market2_0.entity.SteelyardInfo;
import com.lkm.market2_0.m.steelyardstatus.StatusInfo;
import com.lkm.market2_0.m.steelyardstatus.SteelyardStatusManagerModule;
import com.lkm.market2_0.netapi.Api;

import java.io.File;



class OnAppInfoTask extends TaskAdapter {


    private String packageName;
    private SteelyardInfo steelyardInfo;
    private AppInfoScModule appInfoScModule;

    public OnAppInfoTask(AppInfoScModule appInfoScModule, String packageName, SteelyardInfo steelyardInfo) {
        super(new DefaultTaskExecutor(AppConst.getTaskExecutor(), true), OnAppInfoTask.class.getName(), AppConst.getTaskManager2());
        this.appInfoScModule = appInfoScModule;
        this.packageName = packageName;
        this.steelyardInfo = steelyardInfo;
    }

    private File getsteelyardInfo(String packageName) {
        String dir = AppConfig.DataFile.getShardInfoDir(packageName);
        return new File(dir + "steelyardInfo");
    }

    @Override
    public void doExecuting(Object param) {
        super.doExecuting(param);

        mTaskExecutor.executor(new Runnable() {
            @Override
            public void run() {

                File steelyardInfoFile = getsteelyardInfo(packageName);

                AppInfoWrapTo appInfoWrapTo = new AppInfoWrapTo<SteelyardInfo>(Api.host, AppHelp.getLocalVersionName(), null);
                JsonObject appInfoWrapToj = GsonHelp.toJsonObject(appInfoWrapTo);
                JsonObject steelyardInfoj = GsonHelp.toJsonObject(steelyardInfo);

                SteelyardStatusManagerModule statusManagerModule = (SteelyardStatusManagerModule) AppConst.getModuleManager().peekModule(SteelyardStatusManagerModule.class);

                if (statusManagerModule != null && steelyardInfoj != null) {
                    StatusInfo statusInfo = statusManagerModule.getStatusInfoBySteelyardMac(RunTimeData.steelyardInfo.getSteelyardMac());
                    if(statusInfo!=null)
                        steelyardInfoj.addProperty("rv", statusInfo.getVersion());
                }
                appInfoWrapToj.add("info", steelyardInfoj);

                FileHelper.SaveString(appInfoWrapToj.toString(), steelyardInfoFile, AppConst.charset, true);

                appInfoScModule.sendAppInfoBroadcast();
                complete(null);
            }
        });


    }


}
